package com.asia5b.a5mall.middleware.base

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.annotation.FloatRange
import androidx.annotation.UiThread
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.asia5b.a5mall.middleware.utils.DisplayUtils
import com.asia5b.a5mall.middleware.utils.getEventBus
import com.jakewharton.rxbinding3.view.clicks
import io.reactivex.disposables.CompositeDisposable
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit

/**
 * Created by zhangyuncai on 2020/8/19.
 */
abstract class SimpleDialogFragment<VIEWMODEL : SimpleViewModel, DATABINDING : ViewDataBinding> : DialogFragment() {
    abstract val viewModelClazz: Class<VIEWMODEL>
    lateinit var mViewModel: VIEWMODEL
    lateinit var mDataBinding: DATABINDING
    val mCompositeDisposable = CompositeDisposable()
    var isRegisterEventBus: Boolean = false//是否注册广播
    abstract fun getDataBinding(container: ViewGroup?): DATABINDING
    protected val mActivity: SimpleActivity<*, *> by lazy {
        requireActivity() as SimpleActivity<*, *>
    }
    lateinit var rootView: View


    var hasFetchData = false// 标识已经触发过懒加载数据

    //屏幕宽度占比
    @FloatRange(from = 0.0, to = 1.0)
    open val widthPercent = 0.0
    open val widthStyle: Int
        get() {
            if (widthPercent > 0) {
                return (DisplayUtils.getScreenWidthAndHight(context)[0] * widthPercent).toInt()
            }
            return WindowManager.LayoutParams.MATCH_PARENT
        }

    //屏幕高度占比
    @FloatRange(from = 0.0, to = 1.0)
    open val heightPercent = 0.0
    open val heightStyle: Int
        get() {
            if (heightPercent > 0) {
                return (DisplayUtils.getScreenWidthAndHight(context)[1] * heightPercent).toInt()
            }
            return WindowManager.LayoutParams.WRAP_CONTENT
        }

    open val gravity: Int = Gravity.BOTTOM
    open val isStatus = false//是否透明化状态栏
    open val isCancelableOutside = true//是否可以点击外部关闭dialog

    //确定
    protected var mSureClick: ((Any) -> Unit?)? = null

    /**
     * 强转数据
     */
    fun <T> setSureClick(callback: (T) -> Unit) {
        mSureClick = {
            callback.invoke(it as T)
        }
    }

    init {

    }

    override fun onStart() {
        super.onStart()
        val dialog = dialog ?: return
        // 设置宽度为屏宽, 靠近屏幕底部。
        // 设置宽度为屏宽, 靠近屏幕底部。
        val window = getDialog()!!.window ?: return
        //设置窗体背景色透明
        //设置窗体背景色透明
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        //设置宽高
        //设置宽高
        val layoutParams = window.attributes
        layoutParams.width = widthStyle
        layoutParams.height = heightStyle
        //透明度
//        layoutParams.dimAmount = getDimAmount();
        //位置
        //透明度
//        layoutParams.dimAmount = getDimAmount();
        //位置
        layoutParams.gravity = gravity
        window.attributes = layoutParams

        if (isStatus) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isRegisterEventBus) {
            getEventBus().register(this)
        }
        mViewModel = ViewModelProvider(this).get(viewModelClazz)
        mViewModel.loadingLiveData.observe(this, Observer {
            if (requireActivity() != null && (requireActivity() is SimpleActivity<*, *>)) {
                when (it) {
                    0 -> {
                        showLoadingBar("")
                    }
                    1 -> {
                        dismissLoadingBar()
                    }
                    else -> {
                        showLoadingFailureError()
                    }
                }
            }
        })
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        if (this::rootView.isInitialized) {
            if (rootView.parent != null && rootView.parent is ViewGroup) {
                (rootView.parent as ViewGroup).removeView(rootView)
            }
            return rootView
        }
        mDataBinding = getDataBinding(container)

        rootView = mDataBinding.root
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //去除Dialog默认头部
        //去除Dialog默认头部
        val dialog = dialog
        dialog!!.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog!!.setCanceledOnTouchOutside(isCancelableOutside)
//        if (dialog!!.window != null && getDialogAnimationRes() > 0) {
//            dialog!!.window!!.setWindowAnimations(getDialogAnimationRes())
//        }
        if (!hasFetchData) {
            hasFetchData = true
            initView()
            initEvent()
            startObserver()
            initData()
        }
    }

    protected abstract fun initView()
    protected abstract fun initData()
    protected abstract fun initEvent()
    open fun startObserver() {}

    @UiThread
    fun showLoadingBar(content: String) {
        mActivity.showLoadingBar(content)
    }

    @UiThread
    fun dismissLoadingBar() {
        mActivity.dismissLoadingBar()
    }

    @UiThread
    fun showLoadingFailureError(throwable: Throwable? = null) {
        mActivity.showLoadingFailureError(throwable)
    }

    /**
     * 防止双击
     *
     * @param v
     */
    fun onFilterDoubleClick(v: View, listener: View.OnClickListener) {
        val subscribe = v.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe { unit -> listener.onClick(v) }
        mCompositeDisposable.add(subscribe)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        try {
            //在每个add事务前增加一个remove事务，防止连续的add
            manager.beginTransaction().remove(this).commit()
            super.show(manager, tag)
        } catch (e: Exception) {
            //同一实例使用不同的tag会异常,这里捕获一下
            e.printStackTrace()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mCompositeDisposable.dispose()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isRegisterEventBus) {
            getEventBus().unregister(this)
        }
    }

}